package com.woniuxy.business.config;

import com.rabbitmq.client.Channel;
import com.woniuxy.business.dao.CustomerCouponDao;
import com.woniuxy.business.dao.MessageDao;
import com.woniuxy.business.dao.MessageRecordDao;
import com.woniuxy.commons.entity.CustomerCoupon;
import com.woniuxy.commons.entity.MessageRecord;
import com.woniuxy.commons.service.SmsService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Component
public class SmsConsumer {
    @Resource
    private MessageRecordDao messageRecordDao;
    @Resource
    private MessageDao messageDao;
    @Resource
    private SmsService smsService;

    @RabbitListener(queues = "sms_queue")
    public void receive(Channel channel, Message message) throws IOException {
        //解析消息
        String idString = new String(message.getBody(), "utf-8");
        String userId = idString.substring(idString.indexOf(":")+1);
        String messageId = idString.substring(0,idString.indexOf(":"));
        //获取消息内容
        com.woniuxy.commons.entity.Message myMessage = messageDao.findOne(Integer.parseInt(messageId));
        //发送短信，这里写死进行测试
        smsService.send("18581557086","9527");
        //将记录存入数据库
        MessageRecord record = new MessageRecord();
        record.setMessageId(Integer.parseInt(messageId));
        record.setUserId(Integer.parseInt(userId));
        record.setSendTime(new Date());
        messageRecordDao.addOne(record);
        //手动确认消费消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}